﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model;

namespace Logic
{
    public class PhoneInfoLogic
    {
        //public static TB_Phone_Info GetOneModelByRefereePhone(string phone)
        //{
        //    return DB.Context.From<TB_Phone_Info>()
        //        .Where(d => d.RefereePhone == phone)
        //        .ToFirst();
        //}

        /// <summary>
        /// 获取待推荐的号码数据
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public static List<TB_Phone_Info> GetNeedRecommandModelByRefereePhone(string phone, int top)
        {
            int hasRecommand = HasRecommandCount(phone);

            if (hasRecommand >= top)
            {
                return new List<TB_Phone_Info>();
            }
            else
            {
                top = top - hasRecommand;
            }

            return DB.Context.From<TB_Phone_Info>()
                .Where(d => d.RefereePhone == phone && d.bRecommend == 0)
                .OrderBy(d => new { d.PhoneId})
                .Top(top)
                .ToList();
        }

        public static int HasRecommandCount(string phone)
        {
            string start = DateTime.Now.ToString("yyyy-MM-dd" + " 00:00:00");
            string end = DateTime.Now.ToString("yyyy-MM-dd" + " 23:59:59");
            DateTime startTime = DateTime.Parse(start);
            DateTime endTime = DateTime.Parse(end);
            int hasRecommand = DB.Context.From<TB_Phone_Info>()
                .Where(d => d.RefereePhone == phone && d.bRecommend == 1 && d.RecTime > startTime && d.RecTime < endTime)
                .Count();
            return hasRecommand;
        }

        public static int UpdateRecommand(TB_Phone_Info phoneInfo)
        {
            phoneInfo.bRecommend = 1;
            phoneInfo.RecTime = DateTime.Now;
            return DB.Context.Update<TB_Phone_Info>(phoneInfo);
        }

        public static int Insert(TB_Phone_Info phoneInfo)
        {
            phoneInfo.bDownload = 0;
            phoneInfo.bLogin = 0;
            phoneInfo.bRecommend = 0;
            return DB.Context.Insert<TB_Phone_Info>(phoneInfo);
        }
    }
}
